<template>
  <section class="todoapp">
    <TodoHeader :list="list" @addFn="addFn"></TodoHeader>
    <TodoMain :list="showList" @delFn="delFn"></TodoMain>
    <TodoFooter
      @changeType="typeFn"
      :type="flag"
      @clearFn="clearFn"
      :length="this.list.length"
    ></TodoFooter>
  </section>
</template>

<script>
import '@/styles/base.css'
import '@/styles/index.css'

import TodoHeader from '@/components/TodoHeader.vue'
import TodoMain from '@/components/TodoMain.vue'
import TodoFooter from '@/components/TodoFooter'

export default {
  data() {
    return {
      list: JSON.parse(localStorage.getItem('todolist')) || [],
      flag: 'all',
    }
  },
  components: {
    TodoFooter,
    TodoHeader,
    TodoMain,
  },
  methods: {
    addFn(val) {
      let id = this.list.length === 0 ? 100 : this.list.length + 100
      this.list.push({
        id: id,
        name: val,
        isDone: false,
      })
    },
    delFn(index) {
      this.list.splice(index, 1)
    },
    clearFn() {
      this.list = this.list.filter((item) => !item.isDone)
    },
    typeFn(val) {
      this.flag = val
    },
  },
  computed: {
    showList() {
      if (this.flag === 'yes') return this.list.filter((item) => item.isDone)
      else if (this.flag === 'no')
        return this.list.filter((item) => !item.isDone)
      else {
        return this.list
      }
    },
  },
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem('todolist', JSON.stringify(this.list))
      },
    },
  },
}
</script>

<style></style>
